//
//  JKBasePostTableViewController.m
//  Baisi
//
//  Created by albert on 16/3/21.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKBasePostTableViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "JKPostModel.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "JKPostCell.h"
#import "SVProgressHUD.h"
#import "JKCommentViewController.h"
#import "JKNewViewController.h"
#import "JKVideoManager.h"

@interface JKBasePostTableViewController () <UITableViewDataSource, UITableViewDelegate>
/** 当前页 */
@property (nonatomic,assign) NSInteger currentPage;
/** 当加载下一页数据时需要这个参数 */
@property (nonatomic,copy) NSString *maxtime;
/** 请求的参数 */
@property (nonatomic,strong) NSDictionary *params;
/** 上次选中的索引（或者控制器） */
@property (nonatomic, assign) NSInteger lastSeletedIndex;
@end

@implementation JKBasePostTableViewController

static NSString * const postId = @"post";

//到底什么时候需要懒加载啊？？
- (NSMutableArray *)posts{
    if (!_posts) {
        _posts = [NSMutableArray array];
    }
    return _posts;
}

- (UITableView *)tableView{
    
    if (!_tableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:(CGRectMake(0, 0, JKScreenW, JKScreenH)) style:(UITableViewStylePlain)];
        
        [tableView jk_adapt_iOS_11_scrollView];
        tableView.backgroundColor = nil;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.rowHeight = 44;
        
        [self.view addSubview:tableView];
        tableView.tableFooterView = [[UIView alloc] init];
        
        _tableView = tableView;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [JKPostModel mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
//        return @{
//                 @"small_image" : @"image0",
//                 @"large_image" : @"image1",
//                 @"midlle_image" : @"image2",
//                 };
//    }];
//    
//    [JKPostModel mj_setupReplacedKeyFromPropertyName121:^NSString *(NSString *propertyName) {
//        if ([propertyName isEqualToString:@"ID"]) return @"id";
//        
//        return propertyName;
//    }];
    
    //初始化tableView
    [self setupTableView];
    
    //添加刷新控件
    [self setupRefresh];
}

//初始化tableView
- (void)setupTableView{
    
//    [self.tableView jk_adapt_iOS_11_scrollView];
    
    //注册
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([JKPostCell class]) bundle:nil] forCellReuseIdentifier:postId];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    
    //最好写在tableViewController内部
    //设置内容间距，上99（64+35），下49间距（tabBar的高度是49）
    CGFloat topInset = titlesViewY + titlesViewH;
    CGFloat bottomInset = self.tabBarController.tabBar.height;
    self.tableView.contentInset = UIEdgeInsetsMake(topInset, 0, bottomInset, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
}

- (void)setupRefresh{
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewPosts)];
    
    //自动根据下拉比例设置透明度，未下拉时全透明
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    
    //一进来就开始刷新
    [self.tableView.mj_header beginRefreshing];
    
    //MJRefreshBackFooter刚进来时是看不到的
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMorePosts)];
    self.tableView.mj_footer.hidden = YES;
    
    
//    __weak typeof(self) weakSelf = self;
//
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [weakSelf loadMorePosts];
//    }];
    
    //MJRefreshAutoNormalFooter的隐藏放在返回cell数量的方法中就ok了
}

/** a参数 */
- (NSString *)a{
    //如果父控制器是“最新”，则返回newlist，否则返回list
    return [self.parentViewController isKindOfClass:[JKNewViewController class]] ? @"newlist" : @"list";
}

//加载更多的帖子
- (void)loadMorePosts{
    //结束下拉刷新
    [self.tableView.mj_header endRefreshing];
    
    //当前页
    NSInteger currentPage = self.currentPage + 1;
    
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.postType);
    params[@"page"] = @(currentPage);
    params[@"maxtime"] = self.maxtime;
    self.params = params;
    
    //发送请求
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //结束刷新
        [self.tableView.mj_footer endRefreshing];
        
        if (self.params != params) return;
        
        //maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];
        
        //字典转模型
        NSArray *newPosts = [JKPostModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        NSInteger count = self.posts.count;
        
        //添加到数组后面
        [self.posts addObjectsFromArray:newPosts];
        
        //刷新表格！！！！！！
        [self.tableView reloadData];
        
        if (self.posts.count > count) {
            
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:count inSection:0] atScrollPosition:(UITableViewScrollPositionBottom) animated:YES];
        }
        
        //加载成功才设置页面
        self.currentPage = currentPage;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        //结束刷新
        [self.tableView.mj_footer endRefreshing];
        
        //如果请求不一致，直接返回
        if (self.params != params) return;
        
        [JKProgressHUD showErrorWithStatus:@"加载数据失败！"];
    }];
}

//加载新的帖子
- (void)loadNewPosts{
    //结束上拉加载更多
    [self.tableView.mj_footer endRefreshing];
    
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.a;
    params[@"c"] = @"data";
    params[@"type"] = @(self.postType);
    self.params = params;
    
    //发送请求
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //如果请求不一致，直接返回
        if (self.params != params) return;
//        [responseObject writeToFile:@"/Users/albert/Desktop/responseObject.plist" atomically:YES];
        //maxtime
        self.maxtime = responseObject[@"info"][@"maxtime"];
        NSLog(@"%@", responseObject);
        
        //字典转模型
        self.posts = [JKPostModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        //刷新表格！！！！！！
        [self.tableView reloadData];
        
        //结束刷新
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_footer.hidden = NO;
        
        //清空页码
        self.currentPage = 0;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        //如果请求不一致，直接返回
        if (self.params != params) return;
        
        [JKProgressHUD showErrorWithStatus:@"加载数据失败！"];
        
        //结束刷新
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    self.tableView.mj_footer.hidden = (self.posts.count == 0);
    return self.posts.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JKPostCell *cell = [tableView dequeueReusableCellWithIdentifier:postId];
    
    if (cell == nil) {
        
        cell = [[JKPostCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:postId];
    }
    
    //取出模型
    JKPostModel *post = self.posts[indexPath.row];
    cell.post = post;
    
    if (post.type == kPostTypeVideo && !cell.moreClickBlock) {
        
        [cell setMoreClickBlock:^(JKPostCell *cell) {
            
            if ([JKVideoManager videoExistWithUrl:cell.post.videouri]) {
                
                [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)].addAction([JKAlertAction actionWithTitle:@"复制视频地址" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                    
                    [UIPasteboard generalPasteboard].string = cell.post.videouri;
                    
                }]).addAction([JKAlertAction actionWithTitle:@"删除缓存视频" style:(JKAlertActionStyleDestructive) handler:^(JKAlertAction *action) {
                    
                    if ([JKVideoManager deleteVideWithUrl:cell.post.videouri]) {
                        
                        [JKProgressHUD showSuccessWithStatus:@"删除成功！"];
                        
                    }else{
                        
                        [JKProgressHUD showErrorWithStatus:@"删除失败!"];
                    }
                }]).show();
                
                return;
            }
            
            JKAlertView *alertView = [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)].addAction([JKAlertAction actionWithTitle:@"收藏" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                
            }]).addAction([JKAlertAction actionWithTitle:@"举报" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                
            }]);
            
            if (cell.post.videouri.length > 0) {
                
                alertView.addAction([JKAlertAction actionWithTitle:@"复制视频地址" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
                    
                    [UIPasteboard generalPasteboard].string = cell.post.videouri;
                    
                }]);
            }
            
            alertView.show();
        }];
    }
    
    return cell;
}

#pragma mark - <Table view delegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //计算方法写在这里会频繁调用并重复计算，改为写在模型中
    //给模型添加一个额外属性cellHeight，重写getter方法，计算高度
    
    //取出模型
    JKPostModel *post = self.posts[indexPath.row];
    
    return post.cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    JKPostCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    JKCommentViewController *commentVc = [[JKCommentViewController alloc] init];
    
    commentVc.post = self.posts[indexPath.row];
    commentVc.homeSelectCell = cell;
    
    [self.navigationController pushViewController:commentVc animated:YES];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    
    [[JKPostModel topImageCache] removeAllObjects];
}
@end
